/*     */ package com.newcrm.webapi.sub;
/*     */ 
/*     */ import com.newcrm.bean.ProductInfo;
/*     */ import com.newcrm.config.Config;
/*     */ import com.newcrm.config.MyDBSetting;
/*     */ import com.newcrm.db.CompanyExtManager;
/*     */ import com.newcrm.db.CompanyManager;
/*     */ import com.newcrm.db.ConnectionManager;
/*     */ import com.newcrm.db.CustomerCategoryManager;
/*     */ import com.newcrm.db.CustomerFieldManager;
/*     */ import com.newcrm.db.NoteDefaultWordManager;
/*     */ import com.newcrm.db.TaskCategoryManager;
/*     */ import com.newcrm.db.UserManager;
/*     */ import com.newcrm.exception.NotFoundException;
/*     */ import com.newcrm.util.MD5;
/*     */ import com.newcrm.util.Util;
/*     */ import com.newcrm.webapi.AbstractAction;
/*     */ import com.newcrm.webapi.AbstractHttpServlet;
/*     */ import java.io.File;
/*     */ import java.io.FileOutputStream;
/*     */ import java.io.IOException;
/*     */ import java.io.PrintWriter;
/*     */ import java.io.UnsupportedEncodingException;
/*     */ import java.net.URL;
/*     */ import java.net.URLDecoder;
/*     */ import java.security.CodeSource;
/*     */ import java.security.ProtectionDomain;
/*     */ import java.sql.Connection;
/*     */ import java.sql.DriverManager;
/*     */ import java.sql.SQLException;
/*     */ import java.sql.Statement;
/*     */ import java.util.List;
/*     */ import java.util.Properties;
/*     */ import javax.servlet.ServletContext;
/*     */ import javax.servlet.ServletException;
/*     */ import javax.servlet.http.HttpServletRequest;
/*     */ import javax.servlet.http.HttpServletResponse;
/*     */ import org.apache.log4j.Logger;
/*     */ 
/*     */ public class CreateDatabase extends AbstractAction
/*     */ {
/*     */   private static final String USER_ROOT = "root";
/*     */   private static final String DB_PORT = "3306";
/*     */   private static final String DB_LOCALHOST = "localhost";
/*     */   private static final String DB_NAME = "qikebao";
/*  48 */   private String dbIp = null;
/*  49 */   private String dbPort = null;
/*  50 */   private String dbName = null;
/*     */ 
/*  52 */   private String dbUser = null;
/*  53 */   private String dbPassword = null;
/*     */ 
/*  55 */   private String companyName = null;
/*  56 */   private String userId = null;
/*  57 */   private String userName = null;
/*  58 */   private String userPassword = null;
/*  59 */   private String email = null;
/*     */ 
/*  61 */   private String activeCode = null;
/*  62 */   private String checkCode = null;
/*  63 */   private String companyId2 = null;
/*  64 */   private String licenceNum = null;
/*  65 */   private String expiredDate = null;
/*     */ 
/*  67 */   private int companyId = 0;
/*     */ 
/*  69 */   private ServletContext servletContext = null;
/*     */ 
/*  71 */   private static Logger logger = Logger.getLogger(CreateDatabase.class
/*  72 */     .getName());
/*     */ 
/*     */   public CreateDatabase(ServletContext servletContext)
/*     */   {
/*  75 */     this.servletContext = servletContext;
/*     */   }
/*     */ 
/*     */   public CreateDatabase(AbstractHttpServlet servlet) {
/*  79 */     super(servlet);
/*     */   }
/*     */ 
/*     */   public void parse(HttpServletRequest request, HttpServletResponse response)
/*     */     throws IOException, ServletException, NotFoundException
/*     */   {
/*  91 */     this.activeCode = Util.getURLParameter(request.getParameter("activeCode"));
/*  92 */     this.checkCode = Util.getURLParameter(request.getParameter("checkCode"));
/*  93 */     this.companyId2 = Util.getURLParameter(request.getParameter("companyId2"));
/*  94 */     this.licenceNum = Util.getURLParameter(request.getParameter("licenceNum"));
/*  95 */     this.expiredDate = Util.getURLParameter(request.getParameter("expiredDate"));
/*     */ 
/*  97 */     this.dbIp = Util.getURLParameter(request.getParameter("dbIp"));
/*  98 */     this.dbPort = Util.getURLParameter(request.getParameter("dbPort"));
/*  99 */     this.dbName = Util.getURLParameter(request.getParameter("dbName"));
/*     */ 
/* 101 */     this.dbUser = Util.getURLParameter(request.getParameter("dbUser"));
/* 102 */     this.dbPassword = Util.getURLParameter(request.getParameter("dbPassword"));
/*     */ 
/* 104 */     this.companyName = Util.getURLParameter(request.getParameter("companyName"));
/* 105 */     this.userId = Util.getURLParameter(request.getParameter("userId"));
/* 106 */     this.userName = Util.getURLParameter(request.getParameter("userName"));
/* 107 */     this.userPassword = Util.getURLParameter(request
/* 108 */       .getParameter("userPassword"));
/* 109 */     this.email = Util.getURLParameter(request.getParameter("email"));
/*     */ 
/* 111 */     response.setContentType("text/html;charset=utf-8");
/* 112 */     PrintWriter out = response.getWriter();
/* 113 */     out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
/* 114 */     out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\"> ");
/* 115 */     out.println("<head>");
/* 116 */     out.println("  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /> ");
/* 117 */     out.println("  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\" />");
/* 118 */     out.println("  <title>创建数据库</title> ");
/*     */ 
/* 120 */     Connection conn = null;
/* 121 */     Statement statement = null;
/*     */     try
/*     */     {
/* 124 */       Class.forName("com.mysql.jdbc.Driver").newInstance();
/*     */ 
/* 127 */       if (("root".equals(this.dbUser)) && ("localhost".equals(this.dbIp))) {
/* 128 */         StringBuffer url = new StringBuffer();
/* 129 */         url.append("jdbc:mysql://").append(this.dbIp).append(":")
/* 130 */           .append(this.dbPort).append("/?user=").append(this.dbUser)
/* 131 */           .append("&password=").append(this.dbPassword);
/* 132 */         conn = DriverManager.getConnection(url.toString());
/*     */ 
/* 134 */         statement = conn.createStatement();
/*     */         try
/*     */         {
/* 140 */           statement.executeUpdate(String.format(
/* 141 */             "DROP USER '%s'@'localhost'", new Object[] { this.dbName }));
/*     */         } catch (SQLException e) {
/* 143 */           logger.warn("drop user faile ", e);
/*     */         }
/*     */ 
/* 149 */         statement.executeUpdate(String.format(
/* 150 */           "CREATE USER '%s'@'localhost' IDENTIFIED BY '%s'", new Object[] { 
/* 151 */           this.dbName, "crm" }));
/*     */ 
/* 153 */         showMsg(out, "创建数据库用户成功");
/*     */ 
/* 156 */         statement.executeUpdate(String.format(
/* 157 */           "DROP DATABASE IF EXISTS %s", new Object[] { this.dbName }));
/*     */ 
/* 164 */         statement
/* 165 */           .executeUpdate(
/* 166 */           String.format("CREATE DATABASE %s DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci", new Object[] { 
/* 167 */           this.dbName }));
/* 168 */         showMsg(out, "创建数据库 ");
/*     */ 
/* 172 */         statement.executeUpdate(
/* 173 */           String.format("GRANT ALL ON %s.* TO '%s'@'localhost'", new Object[] { 
/* 174 */           this.dbName, this.dbName }));
/*     */ 
/* 176 */         showMsg(out, "数据库用户权限设置成功");
/*     */ 
/* 179 */         this.dbUser = this.dbName;
/* 180 */         this.dbPassword = "crm";
/*     */       }
/*     */     } catch (Exception e) {
/* 183 */       logger.warn("create database failed", e);
/* 184 */       showMsg(out, "数据库操作失败 " + e.getMessage());
/*     */ 
/* 186 */       if (statement != null) {
/*     */         try {
/* 188 */           statement.close();
/*     */         } catch (SQLException se) {
/* 190 */           logger.warn(e);
/*     */         }
/*     */       }
/* 193 */       if (conn != null)
/*     */         try {
/* 195 */           conn.close();
/*     */         } catch (SQLException se) {
/* 197 */           logger.warn(e);
/*     */         }
/*     */     }
/*     */     finally
/*     */     {
/* 186 */       if (statement != null) {
/*     */         try {
/* 188 */           statement.close();
/*     */         } catch (SQLException e) {
/* 190 */           logger.warn(e);
/*     */         }
/*     */       }
/* 193 */       if (conn != null) {
/*     */         try {
/* 195 */           conn.close();
/*     */         } catch (SQLException e) {
/* 197 */           logger.warn(e);
/*     */         }
/*     */       }
/*     */ 
/*     */     }
/*     */ 
/* 203 */     if (!isDefaultDBSetting())
/*     */     {
/* 205 */       saveMyDBSetting(out);
/*     */     }
/*     */     else {
/* 208 */       deleteMyDBSetting(out);
/*     */     }
/*     */ 
/* 211 */     boolean flag = createTable(out);
/* 212 */     if (flag) {
/* 213 */       flag = createCompanyAndUser(out);
/*     */     }
/*     */ 
/* 218 */     if (flag) {
/* 219 */       ProductInfo productInfo = Config.getInstance().productInfo;
/* 220 */       if ("1".equals(productInfo.activeCodeFlag))
/*     */       {
/* 222 */         flag = storeActiveCode(out);
/*     */       }
/*     */     }
/*     */ 
/* 226 */     if (flag) {
/* 227 */       out.println("<script>parent.finish();</script>");
/* 228 */       out.flush();
/*     */     }
/* 230 */     out.println("</head><body></body></html>");
/* 231 */     out.flush();
/* 232 */     out.close();
/*     */   }
/*     */ 
/*     */   private void saveMyDBSetting(PrintWriter out)
/*     */   {
/* 241 */     String path = getClass().getProtectionDomain().getCodeSource()
/* 242 */       .getLocation().toString().substring(6);
/*     */     try {
/* 244 */       path = URLDecoder.decode(path, "utf-8");
/*     */     } catch (UnsupportedEncodingException e) {
/* 246 */       logger.warn(e);
/*     */     }
/*     */ 
/* 249 */     int idx = path.indexOf("WEB-INF");
/* 250 */     path = path.substring(0, idx) + "WEB-INF/classes/";
/*     */ 
/* 252 */     Properties properties = new Properties();
/*     */ 
/* 254 */     StringBuffer jdbcUrl = new StringBuffer("jdbc:mysql://");
/* 255 */     jdbcUrl.append(this.dbIp)
/* 256 */       .append(":")
/* 257 */       .append(this.dbPort)
/* 258 */       .append("/")
/* 259 */       .append(this.dbName)
/* 260 */       .append("?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull");
/* 261 */     properties.setProperty("jdbcUrl", jdbcUrl.toString());
/* 262 */     properties.setProperty("user", this.dbUser);
/* 263 */     properties.setProperty("pwd", this.dbPassword);
/*     */ 
/* 265 */     File myDBSetting = new File(path, "dbsetting.properties");
/* 266 */     FileOutputStream fileOut = null;
/*     */     try {
/* 268 */       if (!myDBSetting.exists()) {
/* 269 */         boolean result = myDBSetting.createNewFile();
/* 270 */         if (!result) {
/* 271 */           showMsg(out, "新的数据库配置文件保存失败 " + path + "dbsetting.properties");
/* 272 */           logger.warn("create db setting failed");
/* 273 */           return;
/*     */         }
/*     */       }
/* 276 */       fileOut = new FileOutputStream(myDBSetting);
/* 277 */       properties.store(fileOut, "DB Setting");
/*     */ 
/* 280 */       MyDBSetting.init();
/* 281 */       ConnectionManager.reConnect();
/* 282 */       showMsg(out, "新的数据库配置文件保存成功 ");
/*     */     }
/*     */     catch (SecurityException e) {
/* 285 */       showMsg(out, "新的数据库配置文件保存失败 " + path + "dbsetting.properties");
/* 286 */       logger.warn(e);
/*     */ 
/* 291 */       if (fileOut != null)
/*     */         try {
/* 293 */           fileOut.close();
/*     */         } catch (IOException se) {
/* 295 */           logger.warn(se);
/*     */         }
/*     */     }
/*     */     catch (IOException e)
/*     */     {
/* 288 */       showMsg(out, "新的数据库配置文件保存失败 " + path + "dbsetting.properties");
/* 289 */       logger.warn(e);
/*     */ 
/* 291 */       if (fileOut != null)
/*     */         try {
/* 293 */           fileOut.close();
/*     */         } catch (IOException se) {
/* 295 */           logger.warn(se);
/*     */         }
/*     */     }
/*     */     finally
/*     */     {
/* 291 */       if (fileOut != null)
/*     */         try {
/* 293 */           fileOut.close();
/*     */         } catch (IOException e) {
/* 295 */           logger.warn(e);
/*     */         }
/*     */     }
/*     */   }
/*     */ 
/*     */   private void deleteMyDBSetting(PrintWriter out)
/*     */   {
/* 309 */     String path = getClass().getProtectionDomain().getCodeSource()
/* 310 */       .getLocation().toString().substring(6);
/*     */ 
/* 312 */     int idx = path.indexOf("WEB-INF");
/* 313 */     path = path.substring(0, idx) + "WEB-INF/classes";
/*     */ 
/* 315 */     File myDBSetting = new File(path + "dbsetting.properties");
/* 316 */     if (!myDBSetting.exists()) {
/* 317 */       return;
/*     */     }
/*     */     try
/*     */     {
/* 321 */       myDBSetting.delete();
/*     */     } catch (SecurityException e) {
/* 323 */       logger.warn("delete db setting failed", e);
/*     */     }
/* 325 */     MyDBSetting.init();
/* 326 */     ConnectionManager.reConnect();
/* 327 */     showMsg(out, "默认系统配置的情况下，删除之前的个性化数据库配置文件 ");
/*     */   }
/*     */ 
/*     */   private boolean isDefaultDBSetting() {
/* 331 */     if (!"root".equals(this.dbIp)) {
/* 332 */       return false;
/*     */     }
/*     */ 
/* 335 */     if (!"3306".equals(this.dbPort)) {
/* 336 */       return false;
/*     */     }
/*     */ 
/* 339 */     if (!"root".equals(this.dbUser)) {
/* 340 */       return false;
/*     */     }
/*     */ 
/* 343 */     if (!"qikebao".equals(this.dbName)) {
/* 344 */       return false;
/*     */     }
/* 346 */     return true;
/*     */   }
/*     */ 
/*     */   private boolean storeActiveCode(PrintWriter out)
/*     */   {
/* 355 */     CompanyExtManager companyExtManager = new CompanyExtManager();
/*     */     try {
/* 357 */       companyExtManager.update(14, 
/* 358 */         this.activeCode, this.companyId, this.userId);
/* 359 */       companyExtManager.update(15, 
/* 360 */         this.companyId2, this.companyId, this.userId);
/* 361 */       companyExtManager.update(16, 
/* 362 */         this.checkCode, this.companyId, this.userId);
/* 363 */       companyExtManager.update(17, 
/* 364 */         this.licenceNum, this.companyId, this.userId);
/* 365 */       companyExtManager.update(18, 
/* 366 */         this.expiredDate, this.companyId, this.userId);
/* 367 */       showMsg(out, "存储激活码成功");
/* 368 */       return true;
/*     */     } catch (Exception e) {
/* 370 */       showMsg(out, "存储激活码失败：" + e.getMessage());
/* 371 */     }return false;
/*     */   }
/*     */ 
/*     */   private boolean createCompanyAndUser(PrintWriter out)
/*     */   {
/* 381 */     CompanyManager companyManager = new CompanyManager();
/*     */     try {
/* 383 */       this.companyId = companyManager.add(this.companyName);
/* 384 */       showMsg(out, "创建公司信息成功");
/*     */     } catch (Exception e) {
/* 386 */       showMsg(out, "创建公司信息失败：" + e.getMessage());
/* 387 */       return false;
/*     */     }
/*     */ 
/* 390 */     if (this.companyId <= 0) {
/* 391 */       showMsg(out, "创建公司信息失败");
/* 392 */       return false;
/*     */     }
/*     */ 
/* 395 */     UserManager userManager = new UserManager();
/*     */     try {
/* 397 */       userManager.addAdmin(this.userId, this.userName, this.email, "", "", "", 
/* 398 */         MD5.getMD5(this.userPassword), this.companyId);
/* 399 */       showMsg(out, "创建管理员信息成功");
/*     */     } catch (Exception e) {
/* 401 */       showMsg(out, "创建管理员信息失败:" + e.getMessage());
/* 402 */       return false;
/*     */     }
/*     */ 
/* 405 */     TaskCategoryManager taskCategoryManager = new TaskCategoryManager();
/*     */     try {
/* 407 */       taskCategoryManager.init(this.companyId, this.userId);
/* 408 */       showMsg(out, "初始化任务分类信息成功");
/*     */     } catch (Exception e) {
/* 410 */       showMsg(out, "初始化任务分类信息失败：" + e.getMessage());
/* 411 */       return false;
/*     */     }
/*     */ 
/* 414 */     CustomerFieldManager customerFieldManager = new CustomerFieldManager();
/*     */     try {
/* 416 */       customerFieldManager.init(this.companyId, this.userId);
/* 417 */       showMsg(out, "初始化子定义字段信息成功");
/*     */     } catch (Exception e) {
/* 419 */       showMsg(out, "初始化子定义字段信息失败：" + e.getMessage());
/* 420 */       return false;
/*     */     }
/*     */ 
/* 423 */     CustomerCategoryManager customerCategoryManager = new CustomerCategoryManager();
/*     */     try {
/* 425 */       customerCategoryManager.init(this.companyId, this.userId);
/* 426 */       showMsg(out, "初始化客户分类信息成功");
/*     */     } catch (Exception e) {
/* 428 */       showMsg(out, "初始化客户分类信息失败：" + e.getMessage());
/* 429 */       return false;
/*     */     }
/*     */ 
/* 432 */     NoteDefaultWordManager noteDefaultWordManager = new NoteDefaultWordManager();
/* 433 */     noteDefaultWordManager.init(this.companyId, this.userId);
/* 434 */     showMsg(out, "初始化默认回复内容成功");
/*     */ 
/* 436 */     return true;
/*     */   }
/*     */ 
/*     */   private boolean createTable(PrintWriter out)
/*     */   {
/* 445 */     Connection conn = ConnectionManager.getInstance().getConnection();
/* 446 */     if (conn == null) {
/* 447 */       showMsg(out, "数据库连接失败");
/* 448 */       return false;
/*     */     }
/* 450 */     showMsg(out, "开始创建数据库表");
/* 451 */     Statement statement = null;
/*     */     try {
/* 453 */       statement = conn.createStatement();
/*     */ 
/* 455 */       String sqlFilePath = this.servletContext
/* 456 */         .getRealPath("sql/createTable.sql");
/* 457 */       List sqls = Util.readSQL(sqlFilePath);
/* 458 */       boolean hasFailed = false;
/* 459 */       for (Object sql : sqls) {
/* 460 */         String name = getTableName(sql.toString());
/* 461 */         boolean flag = false;
/*     */         try {
/* 463 */           statement.executeUpdate(sql.toString());
/* 464 */           flag = true;
/*     */         } catch (SQLException e) {
/* 466 */           logger.warn(e);
/*     */         }
/* 468 */         if ((name != null) && (name.length() > 0)) {
/* 469 */           if (flag) {
/* 470 */             showMsg(out, "建立数据表 &nbsp;&nbsp;" + name + 
/* 471 */               "&nbsp;&nbsp;...&nbsp;成功 ");
/*     */           } else {
/* 473 */             showMsg(out, "建立数据表 &nbsp;&nbsp;" + name + 
/* 474 */               "&nbsp;&nbsp;...&nbsp;失败 ");
/* 475 */             hasFailed = true;
/*     */           }
/*     */         }
/*     */       }
/* 479 */       if (hasFailed)
/* 480 */         showMsg(out, "数据库表创建过程中有错误，请解决后重新执行。");
/*     */       else
/* 482 */         showMsg(out, "数据库表全部创建完成");
/*     */     }
/*     */     catch (SQLException e) {
/* 485 */       logger.warn(e);
/*     */ 
/* 487 */       if (statement != null)
/*     */         try {
/* 489 */           statement.close();
/*     */         } catch (SQLException se) {
/* 491 */           logger.warn(se);
/*     */         }
/*     */       try
/*     */       {
/* 495 */         conn.close();
/*     */       } catch (SQLException se) {
/* 497 */         logger.warn(se);
/*     */       }
/*     */     }
/*     */     finally
/*     */     {
/* 487 */       if (statement != null)
/*     */         try {
/* 489 */           statement.close();
/*     */         } catch (SQLException e) {
/* 491 */           logger.warn(e);
/*     */         }
/*     */       try
/*     */       {
/* 495 */         conn.close();
/*     */       } catch (SQLException e) {
/* 497 */         logger.warn(e);
/*     */       }
/*     */     }
/* 500 */     return true;
/*     */   }
/*     */ 
/*     */   private void showMsg(PrintWriter out, String msg)
/*     */   {
/* 509 */     out.println("<script>parent.showMsg('" + 
/* 510 */       Util.UEncode(msg.replaceAll("\r\n", "").replaceAll("\n", "")
/* 511 */       .replaceAll("'", "\"")) + "'); </script>");
/* 512 */     out.flush();
/*     */   }
/*     */ 
/*     */   private String getTableName(String sql)
/*     */   {
/* 522 */     if ((sql == null) || (sql.trim().length() == 0)) {
/* 523 */       return null;
/*     */     }
/*     */ 
/* 526 */     if (!sql.startsWith("create table")) {
/* 527 */       return null;
/*     */     }
/*     */ 
/* 530 */     int idx = sql.indexOf("(");
/* 531 */     if (idx <= 0) {
/* 532 */       return null;
/*     */     }
/*     */ 
/* 535 */     int idx2 = sql.indexOf("table");
/* 536 */     if (idx2 <= 0) {
/* 537 */       return null;
/*     */     }
/*     */ 
/* 540 */     return sql.substring(idx2 + "table".length(), idx).trim();
/*     */   }
/*     */ }

/* Location:           C:\E\referenceProject\CRM参考\qikebao\WEB-INF\lib\qikebao.jar
 * Qualified Name:     com.newcrm.webapi.sub.CreateDatabase
 * JD-Core Version:    0.6.1
 */